package com.hyh.parser;

import java.net.DatagramPacket;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hyh.manager.ClientManager;
import com.hyh.model.Client;
import com.hyh.request.BaseRequest;
import com.hyh.request.BaseRequest.MsgType;
import com.hyh.request.FrameTransferRequest;
import com.hyh.request.HeartBeatRequest;
import com.hyh.response.BaseResponse;
import com.hyh.response.FrameTransferResponse;
import com.hyh.response.HeartBeatResponse;
import com.hyh.util.DateUtil;

public class BaseParser {
	
	private Gson gson;
	
	
	public BaseParser(){
		GsonBuilder builder = (new GsonBuilder()).disableHtmlEscaping();
		gson = builder.create();
	}
	
	public DatagramPacket parse(DatagramPacket packet){
		
		String json = new String(packet.getData(),0,packet.getLength());
		BaseRequest request = gson.fromJson(json, BaseRequest.class);
		return handlerRequest(request.MessageType,json, packet);
	}
	
	protected DatagramPacket handlerRequest(String messageType,String json,DatagramPacket packet){
		
		BaseResponse response = null;
		DatagramPacket datagramPacket=null;
		String jsonStr;
		Client client;
		switch(messageType){
			case MsgType.HeartBeatRequest:
				HeartBeatRequest heartBeatRequest = gson.fromJson(json, HeartBeatRequest.class);
				client = new Client(heartBeatRequest.Body.id,packet.getAddress(),packet.getPort());
				ClientManager.getInstance().add(client);
				response = new HeartBeatResponse(heartBeatRequest);
				jsonStr = response.toJson();
				datagramPacket = new DatagramPacket(jsonStr.getBytes(), jsonStr.length());
				System.out.println("HeartBeatRequest id="+heartBeatRequest.Body.id+";"+packet.getAddress().getHostAddress()+":"+packet.getPort()+" "+DateUtil.getDate());
				break;
			case MsgType.FrameTransferRequest:
				FrameTransferRequest frameTransferRequest = gson.fromJson(json, FrameTransferRequest.class);
				client = ClientManager.getInstance().get(frameTransferRequest.Body.toId);
				if(client!=null){
					response = new FrameTransferResponse(frameTransferRequest);
					jsonStr = response.toJson();
					datagramPacket = new DatagramPacket(jsonStr.getBytes(), jsonStr.length(),client.getAddr(),client.getPort());
				}
				break;
		}
		return datagramPacket;
	}
	
}
